package com.satan.fmmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.satan.fmmall.entity.User;
import com.satan.fmmall.mapper.UserMapper;
import com.satan.fmmall.service.UserService;
import com.satan.fmmall.utils.JwtUitls;
import com.satan.fmmall.vo.ResCode;
import com.satan.fmmall.vo.ResultVo;
import com.satan.fmmall.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @date 2022/3/28 17:49
 * @Version 1.0
 */
@Service
@Scope("singleton")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    @Transactional
    public ResultVo userResgit(String username, String password) {
        synchronized (this) {
            //1.根据用户名查询用户是否进行了注册
            User user = queryUserByName(username);
            //2.如果没有注册则进行保存操作
            if (user == null) {
                String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
                user = new User();
                user.setUsername(username);
                user.setPassword(md5Pwd);
                user.setUserImg("http://192.168.120.130:9999/fmall-images/images/default.png");
                int i = userMapper.insert(user);
                if (i > 0) {
                    return ResultVo.success(null);
                } else {
                    return ResultVo.fail(ResCode.REGIST_FAILD);
                }
            } else {
                return ResultVo.fail(ResCode.ACCOUNT_EXIST);
            }
        }

    }

    @Override
    public ResultVo checkLogin(String username, String password) {
        User user = queryUserByName(username);
        if (user==null){
            return ResultVo.fail(ResCode.ACCOUNT_OR_PASSWORD_ERROR);
        }else {
            String md5Pwd=DigestUtils.md5DigestAsHex(password.getBytes());
            if (md5Pwd.equals(user.getPassword())){
                String token = JwtUitls.createToken(user.getUserId());
                redisTemplate.opsForValue().set("TOKEN_USER_" + user.getUserId(), JSON.toJSONString(user), 1, TimeUnit.DAYS);
                return ResultVo.success(token);
            }else {
                return ResultVo.fail(ResCode.ACCOUNT_OR_PASSWORD_ERROR);
            }
        }
    }

    @Override
    public ResultVo getUserInfoByToken(String token) {
        ResultVo resultVo = JwtUitls.checkToken(token);
        if (resultVo.getCode()!=200){
            return resultVo;
        }
        Integer userId = JwtUitls.getUserId(token);
        String userJson = redisTemplate.opsForValue().get("TOKEN_USER_" + userId);
        if (StringUtils.isEmpty(userJson)){
            return ResultVo.fail(ResCode.NO_LOGIN);
        }
        User user = JSON.parseObject(userJson, User.class);
        UserVo userVo=new UserVo();
        BeanUtils.copyProperties(user, userVo);
        //System.out.println("userVo = " + userVo);
        return ResultVo.success(userVo);
    }

    @Override
    public ResultVo logout(String token) {
        Integer userId = JwtUitls.getUserId(token);
        Boolean delete = redisTemplate.delete("TOKEN_USER_" + userId);
        if (delete){
          return ResultVo.success(null);
        }else {
            return ResultVo.fail(ResCode.LOGOUT_ERROR);
        }

    }


    public User queryUserByName(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
}
